<?php
/*----------------------------------------------------------------------
 * 公用函数模型管理
 * Author: ming.nie
----------------------------------------------------------------------*/

namespace Common\Logic;

class DataSyncLogic
{
    /**
     * 平台数据同步：影院更新数据到云平台
     * @param  array:
     *          $params['module'] = 'member_list'
     *          数据模块
     *          member_list：会员
     *          video_hall_list：影厅
     *          cinema_info：影院信息
     *          reserve_status：影院预定状态
     *          
     *          $params['row'] = array('member_id'=>1, ...) //数据记录
     * @return array
     * @author ming.nie
     */
    public function getCinemaDdata($params)
    {
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0, 'status_message'=>'数据同步操作失败'),
            1 => array('status_code'=>1, 'status_message'=>'数据同步操作成功'),
            3 => array('status_code'=>3, 'status_message'=>'参数错误'),
        );
        $status_code = 0;
        if(array_key_exists('module', $params) && $params['module']
           && array_key_exists('row', $params) && $params['row']) {
            
            $db_rs = 0;
            $current_time = time();
            $commonLogic = new \Common\Logic\CommonLogic();
            
            if('member_list' == $params['module']) {
                //会员
                $model = M('Member');
                $condition = array();
                $condition['host_name'] = $params['row']['host_name'];
                $condition['id'] = $params['row']['id'];
                $check_rs = $model->where($condition)->find();
                if($check_rs) {
                    $params['row']['uptime'] = $current_time;
                    $db_rs = $model->where($condition)->data($params['row'])->save();
                } else {
                    $db_rs = $model->data($params['row'])->add();
                }
            } else if('video_hall_list' == $params['module']) {
                //影厅
                $model = M('CinemaHall');
                $condition = array();
                $condition['host_name'] = $params['row']['host_name'];
                $condition['hall_id'] = $params['row']['hall_id'];
                $check_rs = $model->where($condition)->find();
                if($check_rs) {
                    $params['row']['update_time'] = $current_time;
                    $db_rs = $model->where($condition)->data($params['row'])->save();
                } else {
                    $db_rs = $model->data($params['row'])->add();
                }
                //拉取图片
                if(array_key_exists('images', $params['row'])) {
                    
                    //影院信息
                    $cinemaModel = M('CinemaHost');
                    $cinema_condition = array();
                    $cinema_condition['host_name'] = $params['row']['host_name'];
                    $cinema = $cinemaModel->where($cinema_condition)->find();
                    
                    $images = unserialize($params['row']['images']);
                    if(is_array($images) && $images && $cinema) {
                        foreach($images as $key => $value) {
                            getRemoteImg('http://'.$cinema['host_ip'].$value, $_SERVER['DOCUMENT_ROOT'].'/Uploads/hall/');
                            $img_arr = array();
                            $img_arr['picpath'] = $value;
                            $img_arr['picsize_arr'] = serialize(array('200x133', '678x454'));
                            $commonLogic->setRemoteThumbs($img_arr);
                        }
                    }
                }
            } else if('cinema_info' == $params['module']) {
                //影院信息
                $model = M('CinemaHost');
                $condition = array();
                $condition['host_name'] = $params['row']['host_name'];
                $check_rs = $model->where($condition)->find();
                if($check_rs) {
                    $params['row']['update_time'] = $current_time;
                    $db_rs = $model->where($condition)->data($params['row'])->save();
                    //拉取图片
                    if(array_key_exists('cinema_logo', $params['row'])
                       && $params['row']['cinema_logo']) {
                        getRemoteImg('http://'.$check_rs['host_ip'].$params['row']['cinema_logo'], $_SERVER['DOCUMENT_ROOT'].'/Uploads/logo/');
                        $img_arr = array();
                        $img_arr['picpath'] = $params['row']['cinema_logo'];
                        $img_arr['picsize_arr'] = serialize(array('80x80'));
                        $commonLogic->setRemoteThumbs($img_arr);
                    }
                    if(array_key_exists('cinema_img', $params['row'])
                       && $params['row']['cinema_img']) {
                        getRemoteImg('http://'.$check_rs['host_ip'].$params['row']['cinema_img'], $_SERVER['DOCUMENT_ROOT'].'/Uploads/logo/');
                        $img_arr = array();
                        $img_arr['picpath'] = $params['row']['cinema_img'];
                        $img_arr['picsize_arr'] = serialize(array('750x378', '392x392', '220x146', '220x132'));
                        $commonLogic->setRemoteThumbs($img_arr);
                    }
                }
            } else if('reserve_status' == $params['module'] || 'pre_order_count' == $params['module']) {
                //影院预定状态
                $model = M('CinemaHost');
                $condition = array();
                $condition['host_name'] = $params['row']['host_name'];
                $check_rs = $model->where($condition)->find();
                if($check_rs) {
                    $params['row']['update_time'] = $current_time;
                    $db_rs = $model->where($condition)->data($params['row'])->save();
                }
            }
            
            if($db_rs) {
                $status_code = 1;
                //更新对应的缓存信息

                /**
                 * 删除会员缓存
                 * Geng.Lin 2015-10-21
                 */
                if('member_list' == $params['module']) {
                    //todo..
                }
                if('cinema_info' == $params['module'] || 'pre_order_count' == $params['module'] || 'video_hall_list' == $params['module'] || 'reserve_status' == $params['module']){
                    $cinemaLogic = new \Common\Logic\CinemaLogic();
                    $cinemaLogic->updataCache();
                }

            }
            
        } else {
            $status_code = 3;
        }
        
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
    
    /*
     * v2上线，同步更新影院用户到运营平台，只运行一次
     * @return array
     *          $params['host_name'] = 'nmdev_1'
     *          $params['data_list'] = array();
     * @author ming.nie
     */
    public function clearCinemaMemberListV2($params)
    {
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0, 'status_message'=>'数据同步操作失败'),
            1 => array('status_code'=>1, 'status_message'=>'数据同步操作成功'),
            3 => array('status_code'=>3, 'status_message'=>'参数错误'),
        );
        $status_code = 0;
        if(array_key_exists('host_name', $params) && $params['host_name']
           && array_key_exists('data_list', $params)) {
            $status_code = 1;
            $model = M('Member');
            foreach($params['data_list'] as $key => $value) {
                $condition = array();
                $condition['host_name'] = $params['host_name'];
                $condition['id'] = $value['id'];
                $check_rs = $model->where($condition)->find();
                if(!$check_rs) {
                    $value['host_name'] = $params['host_name'];
                    $model->data($value)->add();
                }
            }
        } else {
            $status_code = 3;
        }
        
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
    
    /*
     * 平台数据同步：同步影院的影厅是否可以在线预定状态到云平台
     * @author ming.nie
     */
    public function refreshVideoHallIsOnlineBooking($params)
    {
        $model = M('CinemaHall');
        
        //是否有数据更新
        $is_update = false;
        foreach($params['data_list'] as $key => $value) {
            $update_data = array();
            $update_data['is_online_booking'] = $value['is_online_booking'];
            $update_data['status'] = $value['status'];
            $condition = array();
            $condition['hall_id'] = $value['hall_id'];
            $condition['host_name'] = $params['host_name'];
            $rs = $model->data($update_data)->where($condition)->save();
            if($rs && !$is_update) {
                $is_update = true;
            }
        }
        
        //有数据更新，更新web平台缓存
        if($is_update) {
            $cinemaLogic = new \Common\Logic\CinemaLogic();
            $cinemaLogic->updataCache();
        }
        return true;
    }
    
    /*
     * 线下系统，重新安装，业务数据记录刷新
     * @author ming.nie
     */
    public function refreshCinemaSystemBusinessRows($params)
    {
        $result = array();
        $result['max_order_id'] = $result['max_org_play_id'] = 1;
        
        $model = M();
        
        //影院系统订单编号基于线上同步订单的最大编号，进行重置
        $order_sql = 'SELECT host_name,order_id FROM mt_cinema_order WHERE host_name = "'.$params['host_name'].'" ORDER BY order_id DESC LIMIT 0,1';
        $order_rs = $model->query($order_sql);
        if($order_rs) {
            $result['max_order_id'] = $order_rs[0]['order_id'];
        }

        //线下重装后，net影厅逻辑删除
        if($params['host_name']){
            $modelCinemaHall = M('CinemaHall');
            $update_data['status'] = 0;
            $condition = array();
            $condition['host_name'] = $params['host_name'];
            $modelCinemaHall->data($update_data)->where($condition)->save();
        }

        //查询org_play最大id
        $options['where']['host_name'] = array('eq',$params['host_name']);
        $options['field'] = 'id,type';
        $cinema = D('Common/CinemaHost')->getOne($options);
        if(!$cinema)return $result;
        $db = 'mysql://'.C('DB_USER').':'.C('DB_PWD').'@'.C('DB_HOST').':'.C('DB_PORT').'/'.C('DB_CONFIG'.$cinema['type']);
        $sql = 'SELECT MAX(`id`) AS max_id FROM '.trueTab('org_play_'.$cinema['id']).' LIMIT 0,1';
        $max_org_play_id = M()->db($cinema['type'],$db)->query($sql)[0]['max_id'];
        $result['max_org_play_id'] = $max_org_play_id ? $max_org_play_id : 1;

        //影厅数据表数据
        $result['halls'] = D('OrgHall')
            ->where(['cinema_id'=>$cinema['id']])
            ->field('sub_id AS id,sn,cost,ntime,ctime,utime,2 AS `status`')
            ->select();
        return $result;
    }
    //记录智慧医疗订单数据
    public function syncYlOrderData($params){
        if($params){
            $C=M('cinema_host');
            $Yl=M('ylOrder');
            $where['host_name']=$params['host_name'];
            $tag=$C->where($where)->count('id');
            $msg['status']=0;
            $msg['message']='failed';
            if($tag){
                $data=array();
                foreach ($params['data_list'] as $val){
                    $val['host_name']=$params['host_name'];
                    unset($val['id']);
                    $data[]=$val;
                }
                $res=$Yl->addAll($data);
                if(!$res){
                   file_put_contents('/data/logs/yl_order.log',json_encode($data).PHP_EOL,8);
                }else{
                    $msg['status']=1;
                    $msg['message']='success';
                }
            }
            echo json_encode($msg);
        }
    }
}
